package org.jeecg.modules.simulator.model.line.station.strategy;

import org.jeecg.modules.simulator.model.line.station.equipment.StationEntryExitGate;
import org.jeecg.modules.simulator.model.person.Person;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: 平均分配人到各个进站口
 * @description:
 * @author: renzhg
 * @create: 2024-09-11 10:06
 **/
public class AverageEntryExitGateStage implements IEntryExitGateStage {
    @Override
    public void assignPerson(Map<String, Person> personMap, Map<String, StationEntryExitGate> entryExitGateMap) throws Exception {
        if(entryExitGateMap.size()==0){
            throw new Exception();
        }
        int personSize = personMap.size();
        int entryExitGateSize=entryExitGateMap.size();
        int averagePersonSize = (int )(personSize / entryExitGateSize);
        List<Map<String, Person>> splitMapList =splitMap(personMap,averagePersonSize);
        int count=0;
        for (Map.Entry<String, StationEntryExitGate> entry : entryExitGateMap.entrySet()) {
            entry.getValue().getWillEntryPersonMap().clear();
            if(count>=splitMapList.size()){
                break;
            }

            entry.getValue().setWillEntryPersonMap(splitMapList.get(count));
            count++;
        }


    }

    public  List<Map<String, Person>> splitMap(Map<String, Person> originalMap, int chunkSize) {
        List<Map<String, Person>> mapChunks = new ArrayList<>();
        Map<String, Person> currentChunk = new HashMap<>();

        int count = 0;
        for (Map.Entry<String, Person> entry : originalMap.entrySet()) {
            currentChunk.put(entry.getKey(), entry.getValue());
            count++;

            if (count == chunkSize) {
                mapChunks.add(currentChunk);
                currentChunk = new HashMap<>();
                count = 0;
            }
        }

        // Add the last chunk if it has entries
        if (!currentChunk.isEmpty()) {
            mapChunks.add(currentChunk);
        }

        return mapChunks;
    }
}
